//
//  NXThirdStepViewController.m
//  BiologyLibrary
//
//  Created by 朱进 on 16/7/3.
//  Copyright © 2016年 youxh. All rights reserved.
//

#import "NXThirdStepViewController.h"
#import "NXFourthStepViewController.h"
@implementation NXThirdStepViewController

static const NSString * KEY_STEP  = @"step3";


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNaviBarTitle:self.NewRecordArray.firstObject.name];
    _contentTableView = [[UITableView alloc] initWithFrame:
                         CGRectMake(10, fHeight_Nav + fHeight_StatueBar + 10, fWidth_Current - 20, fHeight_Current - fHeight_Nav -fHeight_StatueBar - 60)];
    _contentTableView.backgroundColor = [UIColor clearColor];
    _contentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _contentTableView.dataSource = self;
    _contentTableView.delegate = self;
    [self.view addSubview:_contentTableView];
    time1Arr = [NSMutableArray arrayWithCapacity:0];
    time2Arr = [NSMutableArray arrayWithCapacity:0];
    for (Record *model in self.NewRecordArray) {
        NSInteger section = 0;
        if ([[model getDetailDict] objectForKey:KEY_STEP] &&
            [[[model getDetailDict] objectForKey:KEY_STEP] count] > section &&
            [[[[model getDetailDict] objectForKey:KEY_STEP] objectAtIndex:section] objectForKey:KEY_RECORD_ANSWER]) {
            NSString *string = [[[[model getDetailDict] objectForKey:KEY_STEP] objectAtIndex:section] objectForKey:KEY_RECORD_ANSWER];
            if ([string isEqualToString:@""]) {
                string=@"未知/不详";
            }
            [time1Arr addObject:string];
        }else
        {
            [time1Arr addObject:@""];
        }
        
        section = 1;
        if ([[model getDetailDict] objectForKey:KEY_STEP] &&
            [[[model getDetailDict] objectForKey:KEY_STEP] count] > section &&
            [[[[model getDetailDict] objectForKey:KEY_STEP] objectAtIndex:section] objectForKey:KEY_RECORD_ANSWER]) {
            NSString *string = [[[[model getDetailDict] objectForKey:KEY_STEP] objectAtIndex:section] objectForKey:KEY_RECORD_ANSWER];
            [time2Arr addObject:string];
        }else
        {
            [time2Arr addObject:@""];
        }
    }

    UIImageView*buttomview = [[UIImageView alloc]initWithFrame:CGRectMake(0, fHeight_Current - 50, fWidth_Current, 50)];
    buttomview.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
    [self.view addSubview:buttomview];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, fWidth_Current, 50)];
    label.backgroundColor=[UIColor clearColor];
    label.textAlignment=1;
    label.font=[UIFont systemFontOfSize:14];
    label.textColor=[UIColor lightGrayColor];
    label.text= [NSString stringWithFormat:@"当下是第%ld/%ld步",
                 (long)self.NewRecordArray.firstObject.savedStepCount + 1, (long)self.NewRecordArray.firstObject.allStepCount];
    [buttomview addSubview:label];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;//返回标题数组中元素的个数来确定分区的个数
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.NewRecordArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60+30;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 60;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 60)];
    view.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
    UILabel *titlelab = [[UILabel alloc]initWithFrame:
                         CGRectMake(10, 0, fWidth_Current - 40, 60)];
    titlelab.textColor=[UIColor whiteColor];
    titlelab.backgroundColor=[UIColor clearColor];
    [view addSubview:titlelab];
    
    UIImageView*lineview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 59, fWidth_Current-20, 1)];
    lineview.backgroundColor=[UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:0.3];
    [view addSubview:lineview];
    if (section == 0) {
        titlelab.text=@"3.1、主要动脉血供离断时间";
    }else
    {
        titlelab.text=@"3.2、手术标本离体时间";
    }
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *strIdentifier = [NSString stringWithFormat:@"strIdentifier%ld",(long)indexPath.section];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strIdentifier];
    Record *model = [self.NewRecordArray objectAtIndex:indexPath.row];

    if (cell == nil) {
    
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                      reuseIdentifier:strIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
        
        
        UILabel*recordNameLab=[[UILabel alloc]initWithFrame:CGRectMake(10, 5, fWidth_Current, 30)];
        recordNameLab.tag = 3;
        recordNameLab.backgroundColor=[UIColor clearColor];
        recordNameLab.textColor=[UIColor whiteColor];
        recordNameLab.font=[UIFont systemFontOfSize:16];
        [cell.contentView addSubview:recordNameLab];
        UILabel *dateLabel = [[UILabel alloc]initWithFrame:
                              CGRectMake(10, 30, tableView.frame.size.width - 40, 60)];
        dateLabel.tag = 1;
        dateLabel.backgroundColor = [UIColor clearColor];
        dateLabel.textColor = [UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
        [cell.contentView addSubview:dateLabel];
        
        UIImageView *detailImageView = [[UIImageView alloc] initWithFrame:
                                        CGRectMake(dateLabel.frame.origin.x + dateLabel.frame.size.width,
                                                   dateLabel.frame.origin.y + (dateLabel.frame.size.height - 12) / 2 ,
                                                   12, 12)];
        detailImageView.tag = 2;
        detailImageView.image = [UIImage imageNamed:@"navleft"];
        [cell.contentView addSubview:detailImageView];
    }
    UILabel *dateLabel = [cell.contentView viewWithTag:1];
    UIImageView *detailImageView = [cell.contentView viewWithTag:2];
    UILabel *recordNameLab = [cell.contentView viewWithTag:3];
        if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
            detailImageView.hidden = YES;
        }else{
            detailImageView.hidden = NO;
        }
        recordNameLab.text=[NSString stringWithFormat:@"样本号：%@",model.recordId];

        if(indexPath.section == 0){
        
            
                
                dateLabel.text = time1Arr[indexPath.row];

        }else if (indexPath.section == 1){

           
                dateLabel.text = time2Arr[indexPath.row];
        }

    
    
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==1) {
        return 70.0f;

    }else{
        return 10;
    }
}

- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    if (section==1) {
        UIView *footerView = [[UIView alloc] initWithFrame:
                              CGRectMake(0, 0, tableView.frame.size.width , 50)];
        footerView.backgroundColor = [UIColor clearColor];
        
        if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
            
            UIButton *btn2=[[UIButton alloc]initWithFrame:CGRectMake(0, 10, footerView.frame.size.width, 50)];
            btn2.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            btn2.layer.cornerRadius=5;
            [btn2 setTitle:@"下一步" forState:UIControlStateNormal];
            btn2.clipsToBounds=YES;
            [btn2 addTarget:self action:@selector(nextStepClick) forControlEvents:UIControlEventTouchUpInside];
            [footerView addSubview:btn2];
            return footerView;
        }else{
            
            UIButton *btn1=[[UIButton alloc]initWithFrame:
                            CGRectMake(0, 10, (footerView.frame.size.width - 10) / 2, 50)];
            btn1.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
            btn1.layer.cornerRadius=5;
            [btn1 setTitle:@"取消" forState:UIControlStateNormal];
            [btn1 addTarget:self action:@selector(cancelclick) forControlEvents:UIControlEventTouchUpInside];
            btn1.clipsToBounds=YES;
            [footerView addSubview:btn1];
            UIButton *btn2=[[UIButton alloc]initWithFrame:
                            CGRectMake(btn1.frame.origin.x + btn1.frame.size.width + 10,
                                       btn1.frame.origin.y,
                                       btn1.frame.size.width, btn1.frame.size.height)];
            btn2.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
            btn2.layer.cornerRadius=5;
            [btn2 setTitle:@"保存" forState:UIControlStateNormal];
            btn2.clipsToBounds=YES;
            [btn2 addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
            [footerView addSubview:btn2];
            return footerView;
        }
    }else{
        UIView *footerView = [[UIView alloc] initWithFrame:
                              CGRectMake(0, 0, tableView.frame.size.width , 10)];
        footerView.backgroundColor = [UIColor clearColor];
        return footerView;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    _selectedIndex = indexPath.section;
    if (indexPath.section==0) {
        currentIndex1 = indexPath.row;

    }else{
        currentIndex2 = indexPath.row;

    }

    if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
        
    }else{
    
        if (!_datePickAlertVC) {
            _datePickAlertVC = [UIAlertController alertControllerWithTitle:@"" message:@"\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet];
            //初始化一个标题为“选择时间”，风格是ActionSheet的UIAlertController，其中"\n"是为了给DatePicker腾出空间
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                //点击确定按钮的事件处理
                if(_selectedIndex == 0){
                    if (![time2Arr[currentIndex2] isEqualToString:@""]) {
                        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                        [formatter setDateFormat:@"yyyy-MM-dd hh:mm"];
                        NSDate *date1=[formatter dateFromString:time2Arr[currentIndex2]];
                        NSDate *date2=[formatter dateFromString:[self dateToString:_datePicker.date]];
                        NSTimeInterval secondsInterval= [date1 timeIntervalSinceDate:date2];
                        
                        if (secondsInterval<0) {
                            [self.view makeToast:@"抱歉，标本离体时间不能小于主动脉血供离断时间"];
                            return;
                        }
                        
                    }
                    
                    [time1Arr replaceObjectAtIndex:currentIndex1 withObject:[self dateToString:_datePicker.date]];
                    [tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:currentIndex1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                    
                }else if(_selectedIndex == 1){
                    if (![time1Arr[currentIndex1] isEqualToString:@""]&&![time1Arr[currentIndex1] isEqualToString:@"未知/不详"]) {
                        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                        [formatter setDateFormat:@"yyyy-MM-dd hh:mm"];
                        NSDate *date1=[formatter dateFromString:time1Arr[currentIndex1]];
                        NSDate *date2=[formatter dateFromString:[self dateToString:_datePicker.date]];
                        NSTimeInterval secondsInterval= [date2 timeIntervalSinceDate:date1];
                        
                        if (secondsInterval<0) {
                            [self.view makeToast:@"抱歉，标本离体时间不能小于主动脉血供离断时间"];
                            return;
                        }

                    }
                    [time2Arr replaceObjectAtIndex:currentIndex2 withObject:[self dateToString:_datePicker.date]];
                    [tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:currentIndex2 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
                }
            }];
            
            _datePicker = [[UIDatePicker alloc] init];//初始化一个UIDatePicker
            _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
            [_datePickAlertVC.view addSubview:_datePicker];//将datePicker添加到UIAlertController实例中
            [_datePickAlertVC addAction:cancel];//将确定按钮添加到UIAlertController实例中
        }
        [self presentViewController:_datePickAlertVC animated:YES completion:^{
        }];//通过模态视图模式显示UIAlertController，相当于UIACtionSheet的show方法
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)saveClick{
    BOOL match2 = NO;
    int matchIndex2 = 0;
    for (NSString *time2 in time2Arr) {
        if (time2 == nil || [time2 isEqualToString:@""]) {
            match2 = YES;
            matchIndex2 = [time2Arr indexOfObject:time2];
            break;
        }
    }
    if(match2){
        [self.view makeToast:[NSString stringWithFormat:@"请选择样本号：%@手术标本离体时间！",self.NewRecordArray[matchIndex2].recordId]];
        return;
    }
    BOOL match1 = NO;
    int matchIndex1 = 0;
    for (NSString *time1 in time1Arr) {
        if (time1 == nil || [time1 isEqualToString:@""]) {
            match1 = YES;
            matchIndex1 = [time1Arr indexOfObject:time1];
            break;
        }
    }
    if(match1){
        currentIndex1=matchIndex1;
        NSString *string = [NSString stringWithFormat:@"样本号：%@主要动脉血供离断时间尚未填写，确定将设置为“未知/不详”！",self.NewRecordArray[matchIndex1].recordId];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:string delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
        alert.delegate=self;
        alert.tag=1;
        [alert show];
    
    }else{
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd hh:mm"];
        NSDate *date1=[formatter dateFromString:time1Arr[currentIndex1]];
        NSDate *date2=[formatter dateFromString:time2Arr[currentIndex2]];
        NSTimeInterval secondsInterval= [date2 timeIntervalSinceDate:date1];
        
        if (secondsInterval<0) {
            [self.view makeToast:@"抱歉，标本离体时间不能小于主动脉血供离断时间"];
            return;
        }
        for (Record *model in self.NewRecordArray) {
            [self creatDetailDict:model];
            model.savedStepCount = 3;
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [model update];
            });
        }
        
        
        NXFourthStepViewController *FourthStepVC = [[NXFourthStepViewController alloc] init];
        FourthStepVC.NewRecordArray = self.NewRecordArray;
        [self.navigationController pushViewController:FourthStepVC animated:YES];

    }
    
}
#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag==1) {
        if (buttonIndex==1) {
            [time1Arr replaceObjectAtIndex:currentIndex1 withObject:@"未知/不详"];
            [_contentTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:currentIndex1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            [self saveClick];

        }
    }
}
-(void)cancelclick{
    UIViewController*miloViewControl=(UIViewController *)[[self.navigationController viewControllers]objectAtIndex:1];
    [self.navigationController popToViewController:miloViewControl animated:YES];
}
- (NSString *)dateToString:(NSDate *)date {
    
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT+0800"];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyy-MM-dd hh:mm"];
    
    [formatter setTimeZone:timeZone];
    
    NSString * timeString = [formatter stringFromDate:date];
    
    return timeString;
}

-(void)creatDetailDict:(Record *)model{
    NSInteger index = [self.NewRecordArray indexOfObject:model];
    NSString*date1str=time1Arr[index];
    if ([date1str isEqualToString:@"未知/不详"]) {
        date1str=@"";
    }
    NSDictionary *question1Dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                  @"3.1、主要动脉血供离断时间", KEY_RECORD_QUESTION,
                                  TYPE_QUESTION_DEFAULT, KEY_RECORD_TYPE,
                                  date1str, KEY_RECORD_ANSWER, nil];
    NSDictionary *question2Dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                  @"3.2、手术标本离体时间", KEY_RECORD_QUESTION,
                                  TYPE_QUESTION_DEFAULT, KEY_RECORD_TYPE,
                                  time2Arr[index], KEY_RECORD_ANSWER, nil];
    
    NSArray *qustionArr = [NSArray arrayWithObjects:question1Dict, question2Dict, nil];
    
    NSMutableDictionary *tempDict = [model getDetailDict];
    [tempDict setObject:qustionArr forKey:KEY_STEP];
    [model setDetailDict:tempDict];
    model.recordDetail = [tempDict JSONString];
}

-(void)nextStepClick{
    for (Record *model in self.NewRecordArray) {
        model.savedStepCount = 3;
    }

    NXFourthStepViewController *FourthStepVC = [[NXFourthStepViewController alloc] init];
    FourthStepVC.NewRecordArray = self.NewRecordArray;
    FourthStepVC.fromtype = @"search";
    [self.navigationController pushViewController:FourthStepVC animated:YES];
}

@end
